package com.wenheng.service.Impl;

import com.wenheng.Mapper.EasybuyOrderDetailMapper;
import com.wenheng.Mapper.EasybuyOrderMapper;
import com.wenheng.service.OrderService;
import com.wenheng.vo.entity.EasybuyOrder;
import com.wenheng.vo.entity.EasybuyOrderDetail;
import com.wenheng.vo.entity.EasybuyOrderDetailExample;
import com.wenheng.vo.entity.EasybuyOrderExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Auther: 文恒
 * @Date: 2021/3/26 - 03 - 26 -11:01
 * @Description:com.wenheng.service.Impl
 * @version:1.0
 */
@Service
@Transactional
public class OrderServiceImpl implements OrderService{
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private EasybuyOrderMapper easybuyOrderMapper;
    @Autowired
    private EasybuyOrderDetailMapper easybuyOrderDetailMapper;

    @Override
    public List<EasybuyOrderDetail> findOrder(String orderId) {
        EasybuyOrderDetailExample easy = new EasybuyOrderDetailExample();
        easy.createCriteria().andIdEqualTo(new Integer(orderId));
        return easybuyOrderDetailMapper.selectByExample(easy);
    }

    @Override
    public List<EasybuyOrder> findOrderInfo(String orderNum) {
        EasybuyOrderExample easy = new EasybuyOrderExample();
        EasybuyOrderExample.Criteria criteria = easy.createCriteria();
        criteria.andSerialnumberEqualTo(orderNum);
        return easybuyOrderMapper.selectByExample(easy);
    }

    @Override
    public String createOrderInfo(EasybuyOrder easybuyOrder,Integer proId,Integer proNum,Float quantity) {
        //添加记录一
        Integer i = easybuyOrderMapper.insertSelective(easybuyOrder);
        EasybuyOrderDetail easybuyOrderDetail = new EasybuyOrderDetail();
        easybuyOrderDetail.setOrderid(easybuyOrder.getId());
        easybuyOrderDetail.setProductid(proId);
        easybuyOrderDetail.setQuantity(proNum);
        easybuyOrderDetail.setCost(quantity);
        //添加记录二
        Integer k = easybuyOrderDetailMapper.insertSelective(easybuyOrderDetail);
        //分布式锁 ：
        String redisLock = null;
        if(k>0&&i>0){
            SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
            redisLock = "orderPIC"+sdf.format(new Date());
            redisTemplate.opsForValue().set(redisLock,"1",25, TimeUnit.SECONDS);
        }
        return redisLock;
    }
}
